import React, { useState, useEffect } from 'react';
import { Container, InputGroup, FormControl, Button } from 'react-bootstrap';
import io from 'socket.io-client';

export default function ChatWindow() {
  const [messages, setMessages] = useState([]);
  const [inputMsg, setInputMsg] = useState('');
  const [socket, setSocket] = useState(null);

  useEffect(() => {
    const newSocket = io('http://localhost:3001', {
      auth: { token: localStorage.getItem('token') }
    });

    newSocket.on('newMessage', (msg) => {
      setMessages(prev => [...prev, msg]);
    });

    setSocket(newSocket);
    return () => newSocket.disconnect();
  }, []);

  const sendMessage = () => {
    if (inputMsg.trim()) {
      socket.emit('sendMessage', {
        content: inputMsg,
        receiver: 'public' // 示例使用公共频道
      });
      setInputMsg('');
    }
  };

  return (
    <Container className="chat-container">
      <div className="message-list">
        {messages.map((msg, index) => (
          <div key={index} className="message-bubble">
            <div className="message-header">
              <span className="sender">{msg.sender}</span>
              <span className="time">{new Date(msg.timestamp).toLocaleTimeString()}</span>
            </div>
            <div className="message-content">{msg.content}</div>
          </div>
        ))}
      </div>

      <InputGroup className="message-input">
        <FormControl
          placeholder="输入消息..."
          value={inputMsg}
          onChange={(e) => setInputMsg(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
        />
        <Button variant="primary" onClick={sendMessage}>
          发送
        </Button>
      </InputGroup>
    </Container>
  );
}
